#include "audiodata.h"

#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <QImage>

AudioData::AudioData(QObject *parent) : QObject(parent)
{
    player=CreateZPlay();
    // set graph type to AREA, left channel on top
    player->SetFFTGraphParam(gpGraphType, gtAreaLeftOnTop);
    // set linear scale
    player->SetFFTGraphParam(gpHorizontalScale, gsLinear);

    timer.setInterval(1);
    connect(&timer,SIGNAL(timeout()),this,SLOT(refreshDatas()));

}

void AudioData::setSource(QString source){
    const char* msource=source.toLatin1().data();


    // open file
    int result = player->OpenFile(msource, sfAutodetect);
    if(result == 0)
    {
        // display error message
        qDebug()<<"file open failed"<<player->GetError()<<endl;
        return;
    }

}


void AudioData::playMusic(){
    player->Play();
    timer.start();
    isMusicPlaying=true;
    isPlayingChanged();
}
void AudioData::stopMusic(){
    player->Stop();
    timer.stop();
    isMusicPlaying=false;
    isPlayingChanged();
}
void AudioData::pauseMusic(){
    player->Pause();
    timer.stop();
    isMusicPlaying=false;
    isPlayingChanged();
}
void AudioData::refreshDatas(){

    // get song length
    TStreamInfo info;
    player->GetStreamInfo(&info);

    // check key press
    if(kbhit())
    {
        int a = getch();
        if(a == 'p' || a == 'P')
            player->Pause();
        else if(a=='q'||a=='Q'){
            player->Stop();
        }
    }

    // get stream status to check if song is still playing
    TStreamStatus status;
    player->GetStatus(&status);
    if(status.fPlay == 0)
        return;

    // get current position
    TStreamTime pos;
    player->GetPosition(&pos);
    this->mposition=pos.ms;
    positionChanged();
    int FFTPoints = player->GetFFTGraphParam(gpFFTPoints);
    player->GetFFTData(FFTPoints,fwTriangular,
                       pnHarmonicNumber,
                       pnHarmonicFreq,
                       pnLeftAmplitude,
                       pnRightAmplitude,
                       pnLeftPhase,
                       pnRightPhase);
    amplitudeChanged();
    // draw FFT graph on desktop window
//    player->DrawFFTGraphOnHWND(0, 0, 0, 300, 200);

//    qDebug()<<pnLeftAmplitude[100]<<endl;

}
void AudioData::seekPosition(int ms){
    TStreamTime time;
    time.ms=ms;
    player->Seek(tfMillisecond,&time,smFromBeginning);
}
